﻿/*
    Bisounours Party Updater - Update Source Engine Mods
    Copyright (C) 2012  Louis «Orygin» Geuten and Hekar Khani

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
   
    Bisounours Party Updater  
    Copyright (C) 2012  Louis «Orygin» Geuten and Hekar Khani
    This program comes with ABSOLUTELY NO WARRANTY;
    This is free software, and you are welcome to redistribute it
    under certain conditions;
*/
using System;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;

namespace bpUpdater
{
    class BuUpdater : Updater
    {
        public const string Method = "http";

        private string _gameDir;
        private string _targetUrl;
        private int _serverVersion;
        private int _localVersion;

        public BuUpdater(string gameDir, string targetUrl)
        {
            this._gameDir = gameDir;
            this._targetUrl = targetUrl;
        }

        public void CleanUp()
        {
            // TODO: Cleanup
        }

        public void RetrieveAndUpdate(bool NeedToClean, string updateUrl, 
            string WorkDir, Logger logger)
        {
            for (int i = 0; i < Iterations; i++)
            {
                int currentpatch = (i + 1) + LocalVersion;
                logger.LogLine("Downloading patch #" + currentpatch.ToString());

                string url = updateUrl + currentpatch.ToString() + ".update";
                string dest = WorkDir + @"..\updates\" + currentpatch.ToString() + ".patch";
                WebClient client = new WebClient();
                try
                {
                    client.DownloadFile(new Uri(url), dest);
                    logger.LogLine( "Finished Downloading patch #" + currentpatch.ToString());
                }
                catch (WebException)
                {
                    logger.LogLine("Error, patch #" + currentpatch.ToString() + " not found !!");
                }

                ProcessStartInfo p = new ProcessStartInfo();
                p.FileName = "7zr.exe";
                p.Arguments = "x " + dest + " -o..\\ -aoa";
                p.WorkingDirectory = WorkDir;
                p.WindowStyle = ProcessWindowStyle.Hidden;
                Process x = Process.Start(p);
                x.WaitForExit();

                logger.LogLine("Finished decompression");
                logger.LogLine("----- Patch #" + currentpatch.ToString() + " Applied -----");

                if (NeedToClean)
                {
                    logger.LogLine("Cleaned up patch #" + currentpatch.ToString());
                    File.Delete(dest);
                }
            }
        }

        public void DeleteFiles()
        {
            Directory.Delete(_gameDir);
        }

        public bool InstallRequired
        {
            get
            {
                return false;
            }
        }

        public bool UpdateRequired
        {
            get { return Iterations > 0; }
        }

        public int ServerVersion
        {
            get 
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(_targetUrl);
                myRequest.Method = "GET";
                WebResponse myResponse = myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                string result = sr.ReadToEnd();
                sr.Close();
                myResponse.Close();

                _serverVersion = Convert.ToInt32(result);

                return _serverVersion;
            }
        }

        public int LocalVersion
        {
            get 
            {
                string version = File.ReadAllText(_gameDir);
                _localVersion = Convert.ToInt32(version);
                return _localVersion;
            }
        }

        public int Iterations
        {
            get { return ServerVersion - LocalVersion; }
        }
    }
}
